package com.ogawa.projectcommon.utils

import android.content.Intent
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.ogawa.base.base.BaseResponseBean
import com.ogawa.base.utils.AppManager
import com.ogawa.projectcommon.constants.UrlPathConstant
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

fun ViewModel.launch(
    block: suspend CoroutineScope.() -> Unit,
    onError: (e: Throwable) -> Unit = {},
    onComplete: () -> Unit = {}
): Job {
    return viewModelScope.launch(CoroutineExceptionHandler { _, e ->
        var retE = e
        if ((e.javaClass as Class).name == "java.net.ConnectException") {
            retE = Throwable(message = "网络连接失败")
        }
        onError(retE)
    }) {
        try {
            block.invoke(this)
        } finally {
            onComplete()
        }
    }
}



fun <T> BaseResponseBean<T>.dataConvert(): T {
    if (errCode == "0") {
        return data
    } else {
        LogUtils.e("异常:$errCode  Str: $errMsg")
        if (errCode=="E0300"){ //token失效
            ProjectSpUtils.userInfoLoginOut()
            AppManager.getAppManager().finishAllActivity()
            ARouter.getInstance().build(UrlPathConstant.ACTIVITY_USER_LOGIN)
                .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP)
                .navigation()
        }
        var str =errMsg
        if (str == null || str.isBlank()){
            str = "${errCode}"
        }
        throw Exception(str)
    }
}